﻿using System;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
using Arch;
using InvoiceChecking.Data.SqlClient;
using InvoiceChecking.Data;

public partial class Admin_Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //string encryptData = GlobalUtilities.EncryptData(File.ReadAllText(Server.MapPath("~") + "/ConfigOld.xml"));
            //File.WriteAllText("D:\\Test.xml", encryptData);
            HttpCookie conCookie = Request.Cookies["ICConnectionString"];
            string authUserName = Context.User.Identity.Name.Split('\\')[1];
            tbl_Username.Text = authUserName;
            if (conCookie != null)
                FormsAuthentication.RedirectFromLoginPage(authUserName, false);
            var dataSource = new XmlDataSource { ID = "xmlDataSource", Data = GlobalUtilities.DecryptData(File.ReadAllText(Server.MapPath("~") + "/Config.xml")), XPath = "Servers/Server" };
            ddl_Server.DataSource = dataSource;
            ddl_Server.DataBind();
        }
        //var sb = new StringBuilder();
        //var settings = new XmlWriterSettings();
        ////..settings
        //using (var writer = XmlWriter.Create(sb, settings))
        //{
        //    //...
        //}
        ////http://stackoverflow.com/questions/1564718/using-stringwriter-for-xml-serialization
        //var encoding = new UnicodeEncoding();
        //string s = Convert.ToBase64String(encoding.GetBytes(sb.ToString()));

        //File.WriteAllText("c:\temp.txt", s);
    }
    protected void btn_Submit_Click(object sender, EventArgs e)
    {
        //Request.Cookies["LoginUser"] = new HttpCookie("LoginUser","vy.le");
        string whereExpression = String.Format("UserId='{0}'", tbl_Username.Text);
        int count;
        SqlNetTiersProvider provider = GlobalUtilities.CreateProvider(Server.MapPath("~") + "/Config.xml", ddl_Server.SelectedValue);
        DataRepository.LoadProvider(provider, true);
        DataRepository.InvoiceCheckingUserProvider.GetPaged(whereExpression, "", 0, 1, out count);
        if (count > 0)
        {
            string authUserName = Context.User.Identity.Name.Split('\\')[1];
            HttpCookie con = new HttpCookie("ICConnectionString", ddl_Server.SelectedValue);
            con.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(con);
            FormsAuthentication.RedirectFromLoginPage(authUserName, true);
        }
        else
        {
            div_Error.Visible = true;
        }
    }
}